import 'package:star_author/event_bus/global_event_bus.dart';
import 'package:star_author/event_bus/join_activity_success.dart';
import 'package:star_author/event_bus/user_login_event.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/http/api_manager.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/websocket_manage/websocket_manage.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/src/extension_navigation.dart';
import 'package:provider/provider.dart';

class UserUtil {
  static bool tokenIsInvalid = false;

  static bool isLogin(BuildContext context) {
    return Provider.of<UserProvider>(context, listen: false).isLogin;
  }

  static String getToken(BuildContext context) {
    return Provider.of<UserProvider>(context, listen: false).token ?? "";
  }

  static void setToken(BuildContext context, String token) {
    UserProvider user = Provider.of<UserProvider>(context, listen: false);
    user.set(
      key: 'token',
      value: token,
    );
  }

  static void onLogout(BuildContext context) {
    Provider.of<UserProvider>(context, listen: false)..clearToken();
  }

  static Map? getUserInfo(BuildContext context) {
    return Provider.of<UserProvider>(context, listen: false).user;
  }

  static int getUserId(BuildContext context) {
    return getUserInfo(context)?["id"] ?? 0;
  }

  //没有实名--需要实名
  static bool realNameAuthentication(BuildContext context) {
    return !(Provider.of<UserProvider>(context, listen: false)
            .user?['real_name_authentication'] ??
        false);
  }

  //没有绑定银行卡 --去绑定银行卡
  static bool toBindBankCard(BuildContext context) {
    return (Provider.of<UserProvider>(context, listen: false)
                .user?['adapay_settle_account_id'] ??
            "")
        .toString()
        .isEmpty;
  }

  //激活汇付帐号
  static bool activationBank(BuildContext context) {
    return (Provider.of<UserProvider>(context, listen: false)
                .user?['adapay_member_id'] ??
            "")
        .toString()
        .isEmpty;
  }

  //是否有绑定手机号 需要绑定手机号
  static bool needBindPhone(BuildContext context) {
    return [null, ""].contains(
        Provider.of<UserProvider>(context, listen: false).user?['mobile'] ??
            "");
  }

  //银行卡尾号
  static String bankLastDigits(BuildContext context) {
    UserProvider userProvider =
        Provider.of<UserProvider>(context, listen: false);
    String account_no =
        userProvider.user?['identification']?['account_no'] ?? "";
    String result_Str = '';
    if (account_no.isNotEmpty && account_no.length > 4) {
      result_Str =
          account_no.substring(account_no.length - 4, account_no.length);
    }
    return result_Str;
  }

  static Future<void> onServeUserInfo(BuildContext context,
      {bool isLoading = false}) async {
    var res = await HttpUtil.commonRequest(
      Get.context!,
      ApiManager.current,
      isLoading: isLoading,
      isErrorToast: false,
      queryParameters: {
        "scene": "happ-${Get.currentRoute}",
      },
    );

    Provider.of<UserProvider>(context, listen: false)
        .set(key: 'userInfo', value: res.data);

  }

  //精简版个人信息接口
  static Future<void> onServeUserInfoTiny({bool isLoading = false}) async {
    var res = await HttpUtil.commonRequest(
      Get.context!,
      ApiManager.current_tiny,
      isLoading: isLoading,
      isErrorToast: false,
      queryParameters: {
        "scene": "happ-${Get.currentRoute}",
      },
    );
    Map<dynamic, dynamic> res_user_info = res.data ?? {};
    Map<dynamic, dynamic> res_summary = res_user_info["summary"] ?? {};
    UserProvider provider =
        Provider.of<UserProvider>(Get.context!, listen: false);
    Map<dynamic, dynamic> user = provider.user ?? {};
    int unhandled_treasures_count =
        res_user_info['unhandled_treasures_count'] ?? 0;
    int unread_change_treasures_count =
        res_summary['unread_change_treasures_count'] ?? 0;
    ((res_user_info['summary'] ?? {}) as Map<dynamic, dynamic>)
        .addAll(user['summary'] ?? {} as Map<String, dynamic>);
    res_user_info['summary']['unread_change_treasures_count'] =
        unread_change_treasures_count;
    res_user_info['unhandled_treasures_count'] = unhandled_treasures_count;
    //当服务器的summary数量和本地缓存的不一样的时候 更新数量

    Provider.of<UserProvider>(Get.context!, listen: false)
        .set(key: 'userInfo', value: res_user_info);


  }

  ///登陆成功，绑定极光推送相关
  static void bindJPushConfig(int userId) async {
    await Future.delayed(Duration(seconds: 10));
    LogUtil.v("登陆成功，绑定极光推送相关 $userId");
  }

  static void onChangeUser({int? id}) {
    if (id == null || id == -1) {
      LogUtil.v("onChangeUser return");
      return;
    }
    UserUtil.bindJPushConfig(id);
  }

  static String newbieActivityDialog = 'newbieActivityDialog';

  static String newbieActivityBanner = 'newbieActivityBanner';

  ///新用户逻辑
  static void onLoginCallback(Map map, {String jumpFrom = ''}) async {
    bool newUser = map['new_user'] ?? false;

    int userId = map["user_id"] ?? -1;
    await onServeUserInfo(Get.context!);

    WebSocketManage().changeConnectUrl(userId);
    UserUtil.onChangeUser(id: userId);
    GlobalEventBus().bus.fire(UserLoginEvent(true));

    Function joinActivitiesCallback = () {
      HttpUtil.commonRequest(
        Get.context!,
        '/api/v1/activities',
        isLoading: false,
        isErrorToast: false,
      ).then((value) {
        List allActivitiesList = value.data['data'];

        Map? newbieMap;
        allActivitiesList.forEach((element) {
          if (element['strategy'] == 'newbie' && element['enable'] == true) {
            newbieMap = element;
          }
        });

        if (newbieMap == null) {
          return;
        }
        HttpUtil.commonRequest(
          Get.context!,
          '/api/v1/activities/${newbieMap!['id']}/join',
          isLoading: false,
          isErrorToast: false,
          method: HttpUtil.MethodPost,
        ).then((value) {
          if (value.statusCode == 201) {
            ///参加活动成功，通知其他页面执行对应函数
            ///添加这个event的原因是防止其他页面的活动比join先执行
            GlobalEventBus().bus.fire(
                  JoinActivitySuccess(jumpFromType: jumpFrom),
                );
          }
        });
      });
    };

    ///点击了新人见面礼
    if ([newbieActivityDialog, newbieActivityBanner].contains(jumpFrom)) {
      if (newUser) {
        joinActivitiesCallback();
      } else {
        CustomToast.show("该活动仅限新用户参与");
      }
    }
  }
}
